﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using iTextSharp.tool.xml;
using System.Text.RegularExpressions;

namespace FL.Common
{
  public static class PdfHelper
    {
        /// <summary>
        /// 执行此Url，下载PDF档案
        /// </summary>
        /// <returns></returns>
        public static void DownloadPdf(string url)
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;//定义对象的编码语言,此处或者是gb2312
            //从网址下载Html字串
            string htmlText = wc.DownloadString(url);
            byte[] pdfFile = ConvertHtmlTextToPDF(htmlText);

            FileStream fs = new FileStream(@"D:\范例PDF档.pdf", FileMode.Create, FileAccess.Write);
            fs.Write(pdfFile, 0, pdfFile.Length);
            fs.Close();

        }

        /// <summary>
        /// 将Html文字 输出到PDF档里
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public static byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return null;
            }
            //避免当htmlText无任何html tag标签的纯文字时，转PDF时会挂掉，所以一律加上<p>标签
            htmlText = "<p>" + htmlText + "</p>";

            MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
            byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Stream inCss = new MemoryStream();
            Document doc = new Document(PageSize.A4);//要写PDF的文件，建构子没填的话预设直式A4
            PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
            //指定文件预设开档时的缩放为100%
            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            //开启Document文件
            doc.Open();
         //添加图片
            string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Images\barcode\mains_tongyi.jpg"; //临时文件路径
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
            img.ScalePercent(80f);
            doc.Add(img);

            string apply_noPath = AppDomain.CurrentDomain.BaseDirectory + @"Images\barcode\mains_apply_no.jpg"; //临时文件路径
            iTextSharp.text.Image apply_noImg = iTextSharp.text.Image.GetInstance(apply_noPath);
            apply_noImg.ScalePercent(90f);
            apply_noImg.SetAbsolutePosition(doc.PageSize.Width - 90f - 72f, doc.PageSize.Height - 36f - 100f);
            doc.Add(apply_noImg);
     
         

            //使用XMLWorkerHelper把Html parse到PDF档里
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, inCss, Encoding.UTF8, new UnicodeFontFactory());
            //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
            //将pdfDest设定的资料写到PDF档
            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();
            //回传PDF档案 
            return outputStream.ToArray();
        }
       
    }

    class UnicodeFontFactory : FontFactoryImp
    {
        //arial unicode MS是完整的unicode字型。
        //private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),"arialuni.ttf");
        //标楷体
        private static readonly string simheiPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "simhei.ttf");

        public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
        {
            //可用Arial或标楷体，自己选一个
            BaseFont baseFont = BaseFont.CreateFont(simheiPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            return new Font(baseFont, size, style, color);
        }
    }
}
